import React, { useEffect, useState } from "react";
import '../../appcommon.css';
import styles from './zjc.module.css';
import { useDispatch } from "react-redux";
import { DotLoading, Mask, Toast } from "antd-mobile";
import { saveEvent } from "@/store/actions/saveEvent";
import icon_create_wallet_verify from '@/assets/icon_create_wallet_verify.png'
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";
import ZjcUtil from "@/utils/zjcUtil";
import AppParams from "@/utils/appParams";
import { doLogin } from "@/store/actions/login";
import { LangThai } from '@/utils/langThai';

/**
 * 登录页
 */
export default function ZjcVerify() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    // zjc 列表
    const [zjcFullList, setZjcFullList] = useState([])

    // zjc 列表
    const [zjcList1, setZjcList1] = useState({ label: "", list: [] })

    // zjc 列表
    const [zjcList2, setZjcList2] = useState({ label: "", list: [] })

    // zjc 列表
    const [zjcList3, setZjcList3] = useState({ label: "", list: [] })

    // 文案翻译
    const [curLang, setCurLang] = useState(LangThai);

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //router
    const history = useHistory()

    //清空登录信息
    useEffect(() => {
        //关闭loading
        setMaskVisible(false)

        // 判断助记词是否有效
        let curZjc = ZjcUtil.zjc
        if (!curZjc || curZjc.length <= 0) {
            history.replace('/register');
            return;
        }

        // 分割
        let zjcStringList = curZjc.split(",");
        let allList = zjcStringList.filter((value) => {
            return value.length > 0;
        })

        if (allList.length < 12) {
            history.replace('/register');
            return;
        }

        // 保存
        setZjcFullList(allList);

        // 逻辑测试
        // let allList = ["sdfa1", "eter2", "dfdsafa3", "ddd4", "fsdafa5", "234346", "fdsdd7", "aasd8", "vfvcf9", "cxcd10", "aa11", "bbb12"];

        let getRandomIndex = (max, exclude) => {
            let randomIndex = Math.floor(Math.random() * max);
            while (exclude.includes(randomIndex)) {
                randomIndex = Math.floor(Math.random() * max);
            }
            return randomIndex;
        };

        // 生成3个随机数
        let num1 = getRandomIndex(allList.length, []);
        let num2 = getRandomIndex(allList.length, [num1]);
        let num3 = getRandomIndex(allList.length, [num1, num2]);

        console.log("=====3个随机数 序号:" + num1 + " " + num2 + " " + num3);
        let numValue1 = allList[num1];
        let numValue2 = allList[num2];
        let numValue3 = allList[num3];
        console.log("=====3个随机数 值:" + numValue1 + " " + numValue2 + " " + numValue3);

        // 筛选剩下的项
        let allListTemp = allList.filter((item, index) => {
            let con1 = (numValue1 !== item);
            let con2 = (numValue2 !== item);
            let con3 = (numValue3 !== item);

            return con1 && con2 && con3;
        });
        console.log("=====剩下的数 值:" + allListTemp);

        // 从剩下的项选出9个值
        let getRandomItem = (max, exclude) => {
            let randomItem = Math.floor(Math.random() * max);
            while (exclude.includes(randomItem)) {
                randomItem = Math.floor(Math.random() * max);
            }
            return randomItem;
        };

        let item1 = getRandomItem(allListTemp.length, []);
        let item2 = getRandomItem(allListTemp.length, [item1]);
        let item3 = getRandomItem(allListTemp.length, [item1, item2]);
        let item4 = getRandomItem(allListTemp.length, [item1, item2, item3]);
        let item5 = getRandomItem(allListTemp.length, [item1, item2, item3, item4]);
        let item6 = getRandomItem(allListTemp.length, [item1, item2, item3, item4, item5]);

        let itemValue1 = allListTemp[item1];
        let itemValue2 = allListTemp[item2];
        let itemValue3 = allListTemp[item3];
        let itemValue4 = allListTemp[item4];
        let itemValue5 = allListTemp[item5];
        let itemValue6 = allListTemp[item6];
        console.log("剩下的9个随机 值:" + itemValue1 + " " + itemValue2 + " " + itemValue3 + " " + itemValue4 + " " + itemValue5 + " " + itemValue6);

        let indexFormat = (index) => {
            let nextIndex = (index + 1);
            if (nextIndex >= 10) {
                return "" + nextIndex;
            } else {
                return "0" + nextIndex;
            }
        }

        // 第1行
        let row1 = { label: indexFormat(num1) };
        let list1 = [];
        let listValue1 = [itemValue1, itemValue2];
        let randomIndex1 = Math.floor(Math.random() * 3);
        listValue1.splice(randomIndex1, 0, numValue1);
        console.log("listValue1: " + listValue1);

        for (let i = 0; i < listValue1.length; i++) {
            let selected = false;
            let label = listValue1[i]
            let item = { label: label, selected: selected }
            list1.push(item)
        }
        row1.list = list1
        setZjcList1(row1)

        // 第2行
        let row2 = { label: indexFormat(num2) };
        let list2 = [];
        let listValue2 = [itemValue3, itemValue4];
        let randomIndex2 = Math.floor(Math.random() * 3);
        listValue2.splice(randomIndex2, 0, numValue2);

        for (let i = 0; i < listValue2.length; i++) {
            let selected = false;
            let label = listValue2[i]
            let item = { label: label, selected: selected }
            list2.push(item)
        }
        row2.list = list2
        setZjcList2(row2)

        // 第3行
        let row3 = { label: indexFormat(num3) };
        let list3 = [];
        let listValue3 = [itemValue5, itemValue6];
        let randomIndex3 = Math.floor(Math.random() * 3);
        listValue3.splice(randomIndex3, 0, numValue3);

        for (let i = 0; i < listValue3.length; i++) {
            let selected = false;
            let label = listValue3[i]
            let item = { label: label, selected: selected }
            list3.push(item)
        }
        row3.list = list3
        setZjcList3(row3)

        //打点
        doHitEvent("ZJC_VERIFY_START")

        return () => {
            //打点
            doHitEvent("ZJC_VERIFY_END")
        }
    }, [])

    // 点击列表
    const onHandleVerifyItemClick = (row, index) => {
        console.log("点击列表 " + row + ", " + index);

        if (0 === row) {
            let row = { ...zjcList1 }
            if (!row.list) return

            for (let i = 0; i < row.list.length; i++) {
                let item = row.list[i]
                item.selected = (i === index)
            }
            setZjcList1(row)

        } else if (1 === row) {
            let row = { ...zjcList2 }
            if (!row.list) return

            for (let i = 0; i < row.list.length; i++) {
                let item = row.list[i]
                item.selected = (i === index)
            }
            setZjcList2(row)

        } else if (2 === row) {
            let row = { ...zjcList3 }
            if (!row.list) return

            for (let i = 0; i < row.list.length; i++) {
                let item = row.list[i]
                item.selected = (i === index)
            }
            setZjcList3(row)
        }
    }

    // 点击提交
    const onHandleSubmit = () => {
        console.log("点击提交");
        console.log(zjcFullList);

        // 判断是否选全对
        const index1 = parseInt(zjcList1.label) - 1;
        let isCorrect1 = false;
        let value1 = zjcFullList[index1];
        let resultList1 = zjcList1.list.filter((item) => {
            return (value1 === item.label);
        });
        isCorrect1 = (resultList1.length > 0);

        const index2 = parseInt(zjcList2.label) - 1;
        let isCorrect2 = false;
        let value2 = zjcFullList[index2];
        let resultList2 = zjcList2.list.filter((item) => {
            return (value2 === item.label);
        });
        isCorrect2 = (resultList2.length > 0);

        const index3 = parseInt(zjcList3.label) - 1;
        let isCorrect3 = false;
        let value3 = zjcFullList[index3];
        let resultList3 = zjcList3.list.filter((item) => {
            return (value3 === item.label);
        });
        isCorrect3 = (resultList3.length > 0);

        if (isCorrect1 && isCorrect2 && isCorrect3) {
            // 直接登录
            let inputResult = isInputCorrect();
            if (!inputResult) {
                history.replace('/register');
                return;
            }

            // 登录
            doUserLogin(inputResult.mobile, inputResult.password, inputResult.email, ZjcUtil.ipInfo || {});

        } else {
            Toast.show(curLang.zjcVerifyVerificationFailedPleaseTryAgain);
        }
    };

    // 登录返回
    const onDoUserLoginCallback = (success, data, isNeedToReLogin) => {
        //关闭loading
        setMaskVisible(false)
        console.log('登录返回: ' + success);

        if (success && data) {
            // 处理流程业务
            console.log('跳转首页');
            history.replace('/home');
        } else {
            if (isNeedToReLogin) {
                history.replace('/login')
            }
        }
    };

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //请求登录接口
    const doUserLogin = async (mobile, password, email, ipInfo) => {
        console.log("doLogin: " + mobile + " , " + password + " , " + email);

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const referrerCode = AppParams.referrer
            const tzCode = Intl.DateTimeFormat().resolvedOptions().timeZone;
            const action = doLogin(mobile, password, email, referrerCode || "", ipInfo || {}, tzCode || "", onDoUserLoginCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 判断输入是否合法
    const isInputCorrect = () => {
        //验证手机号
        let mobile = ZjcUtil.mobile;

        //验证密码
        let password = ZjcUtil.password;

        //验证邮箱
        let email = ZjcUtil.email;

        if (!mobile || (mobile.length <= 0)) {
            return null;
        }

        if (!password || (password.length < 8)) {
            return null;
        }

        // if (!email || (!isEmailValid(email))) {
        //     return null;
        // }

        ZjcUtil.mobile = mobile;
        ZjcUtil.password = password;
        ZjcUtil.email = email;

        return { mobile: mobile, password: password, email: email };
    };
    return (
        <div className="pageRoot pageContentPaddingHorizontal16px">
            {/* <NavigateBar theme="white" showLogout={false} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}></NavigateBar> */}

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            {/* 标题 */}
            <div className={styles.zjcTitleLarge}>{curLang.zjcVerifyCreateWallet}</div>
            <div className="pageContentRow pageMarginTop30px">
                <img className={styles.zjcGuideIcon} src={icon_create_wallet_verify} alt="" />
                <div className={styles.zjcTitleDefault}>{curLang.zjcVerifyVerifyYourMnemonicPhrase}</div>
            </div>

            {/* zjc 列表 */}
            <div className={styles.zjcVerifyList}>
                {/* 第1行 */}
                {zjcList1 && (
                    <div className={styles.zjcListVerifyIndex}>{zjcList1.label}</div>
                )}
                <div className={styles.zjcListVerifyContent}>
                    {zjcList1 && zjcList1.list && zjcList1.list.map((value, index) => {
                        if (value.selected) {
                            return (
                                <div className={styles.zjcListVerifyItem} key={index}>
                                    <div className={styles.zjcListVerifyItemLabelSelected} onClick={() => { onHandleVerifyItemClick(0, index) }}>{value.label}</div>
                                </div>
                            )
                        } else {
                            return (
                                <div className={styles.zjcListVerifyItem} key={index}>
                                    <div className={styles.zjcListVerifyItemLabel} onClick={() => { onHandleVerifyItemClick(0, index) }}>{value.label}</div>
                                </div>
                            )
                        }
                    })}
                </div>

                {/* 第2行 */}
                {zjcList2 && (
                    <div className={styles.zjcListVerifyIndex}>{zjcList2.label}</div>
                )}
                <div className={styles.zjcListVerifyContent}>
                    {zjcList2 && zjcList2.list && zjcList2.list.map((value, index) => {
                        if (value.selected) {
                            return (
                                <div className={styles.zjcListVerifyItem} key={index}>
                                    <div className={styles.zjcListVerifyItemLabelSelected} onClick={() => { onHandleVerifyItemClick(1, index) }}>{value.label}</div>
                                </div>
                            )
                        } else {
                            return (
                                <div className={styles.zjcListVerifyItem} key={index}>
                                    <div className={styles.zjcListVerifyItemLabel} onClick={() => { onHandleVerifyItemClick(1, index) }}>{value.label}</div>
                                </div>
                            )
                        }
                    })}
                </div>

                {/* 第3行 */}
                {zjcList3 && (
                    <div className={styles.zjcListVerifyIndex}>{zjcList3.label}</div>
                )}
                <div className={styles.zjcListVerifyContent}>
                    {zjcList3 && zjcList3.list && zjcList3.list.map((value, index) => {
                        if (value.selected) {
                            return (
                                <div className={styles.zjcListVerifyItem} key={index}>
                                    <div className={styles.zjcListVerifyItemLabelSelected} onClick={() => { onHandleVerifyItemClick(2, index) }}>{value.label}</div>
                                </div>
                            )
                        } else {
                            return (
                                <div className={styles.zjcListVerifyItem} key={index}>
                                    <div className={styles.zjcListVerifyItemLabel} onClick={() => { onHandleVerifyItemClick(2, index) }}>{value.label}</div>
                                </div>
                            )
                        }
                    })}
                </div>
            </div>

            {/* 提交 */}
            <div className="pageBtnSubmit pageMarginTop16px" onClick={onHandleSubmit}>{curLang.zjcVerifyVerify}</div>

            {/* 底部提示 */}

            {/* 底部 margin */}
            <div className="pageBottomEdge"></div>

            {/* load mask */}
            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="pageLoadingOverlayContent">
                    <span style={{ fontSize: 24, color: '#3498DB' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div >
    )
}